#!/bin/bash
###############################################################################
#       脚本名称: test_v2_features.sh
#       功能描述: Logger模块v2.0功能集成测试
#       作者: 林再来
#       日期: 2025-10-14
#       版本: 1.0
#       功能:
#           1、测试缓冲区管理
#           2、测试上下文管理
#           3、测试数据脱敏
#           4、测试过滤器系统
#       依赖(插件/命令):
#           无
###############################################################################

set -euo pipefail

# 获取项目根目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

# 测试计数器
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

#-----------------------------------------------------------------------------
# 辅助函数
#-----------------------------------------------------------------------------
function print_header() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║  $1"
    echo "╚══════════════════════════════════════════════════════════════╝"
}

function print_test() {
    echo "  测试: $1"
}

function assert_success() {
    ((TOTAL_TESTS++))
    if [[ $? -eq 0 ]]; then
        echo "    ✓ PASS"
        ((PASSED_TESTS++))
    else
        echo "    ✗ FAIL: $1"
        ((FAILED_TESTS++))
    fi
}

function assert_contains() {
    ((TOTAL_TESTS++))
    local text="$1"
    local pattern="$2"
    
    if echo "$text" | grep -q "$pattern"; then
        echo "    ✓ PASS: 包含 '$pattern'"
        ((PASSED_TESTS++))
    else
        echo "    ✗ FAIL: 不包含 '$pattern'"
        echo "       实际: $text"
        ((FAILED_TESTS++))
    fi
}

#-----------------------------------------------------------------------------
# 测试缓冲区管理
#-----------------------------------------------------------------------------
function test_buffer() {
    print_header "测试缓冲区管理模块"
    
    source "$PROJECT_ROOT/scripts/logger/core/log_buffer.sh"
    
    print_test "初始化缓冲区"
    _log_buffer_init "test_buffer" 5 10
    assert_success
    
    print_test "添加日志到缓冲区"
    for i in {1..3}; do
        _log_buffer_add "test_buffer" "[INFO] 测试日志 $i"
    done
    local size=$(_log_buffer_size "test_buffer")
    [[ $size -eq 3 ]]
    assert_success
    
    print_test "获取缓冲区内容"
    local content=$(_log_buffer_get "test_buffer")
    assert_contains "$content" "测试日志"
    
    print_test "刷新缓冲区"
    _log_buffer_flush "test_buffer" > /dev/null
    size=$(_log_buffer_size "test_buffer")
    [[ $size -eq 0 ]]
    assert_success
}

#-----------------------------------------------------------------------------
# 测试上下文管理
#-----------------------------------------------------------------------------
function test_context() {
    print_header "测试上下文管理模块"
    
    source "$PROJECT_ROOT/scripts/logger/core/log_context.sh"
    
    print_test "初始化上下文"
    _log_context_init
    assert_success
    
    print_test "设置自定义上下文"
    log_context_set "user_id" "12345"
    log_context_set "tenant_id" "tenant-001"
    local user_id=$(log_context_get "user_id")
    [[ "$user_id" == "12345" ]]
    assert_success
    
    print_test "生成追踪ID"
    local trace_id=$(log_context_generate_trace_id "req")
    assert_contains "$trace_id" "req-"
    
    print_test "导出为JSON"
    local json=$(log_context_to_json)
    assert_contains "$json" "user_id"
    assert_contains "$json" "tenant_id"
    
    print_test "批量设置"
    log_context_set_batch "action=login" "ip=192.168.1.100"
    local action=$(log_context_get "action")
    [[ "$action" == "login" ]]
    assert_success
}

#-----------------------------------------------------------------------------
# 测试数据脱敏
#-----------------------------------------------------------------------------
function test_sanitizer() {
    print_header "测试数据脱敏模块"
    
    source "$PROJECT_ROOT/scripts/logger/core/log_sanitizer.sh"
    
    print_test "启用脱敏"
    _log_sanitizer_init "true"
    log_sanitizer_is_enabled
    assert_success
    
    print_test "密码脱敏"
    local result=$(log_sanitize "password=secret123 token=abc123")
    assert_contains "$result" "****"
    
    print_test "手机号脱敏"
    result=$(log_sanitize "手机: 13812345678")
    assert_contains "$result" "138****5678"
    
    print_test "邮箱脱敏"
    result=$(log_sanitize "Email: user@example.com")
    assert_contains "$result" "@example.com"
    
    print_test "自定义规则"
    log_sanitizer_add_rule "order" "ORDER-\d{6}" "ORDER-******"
    result=$(log_sanitize "订单号: ORDER-123456")
    assert_contains "$result" "ORDER-******"
    
    print_test "禁用脱敏"
    log_sanitizer_disable
    result=$(log_sanitize "password=secret123")
    assert_contains "$result" "secret123"
}

#-----------------------------------------------------------------------------
# 测试级别过滤器
#-----------------------------------------------------------------------------
function test_filter_level() {
    print_header "测试级别过滤器"
    
    source "$PROJECT_ROOT/scripts/logger/filters/filter_level.sh"
    
    print_test "初始化过滤器(INFO到ERROR)"
    _filter_level_init "test_filter" "INFO" "ERROR"
    assert_success
    
    print_test "INFO级别应该通过"
    local event='{"level":"INFO","message":"test"}'
    _filter_level_apply "test_filter" "$event"
    assert_success
    
    print_test "DEBUG级别应该拒绝"
    event='{"level":"DEBUG","message":"test"}'
    ! _filter_level_apply "test_filter" "$event"
    assert_success
    
    print_test "FATAL级别应该拒绝"
    event='{"level":"FATAL","message":"test"}'
    ! _filter_level_apply "test_filter" "$event"
    assert_success
}

#-----------------------------------------------------------------------------
# 测试正则过滤器
#-----------------------------------------------------------------------------
function test_filter_pattern() {
    print_header "测试正则过滤器"
    
    source "$PROJECT_ROOT/scripts/logger/filters/filter_pattern.sh"
    
    print_test "初始化过滤器"
    _filter_pattern_init "test_filter"
    assert_success
    
    print_test "添加包含模式"
    _filter_pattern_add_include "test_filter" "user"
    _filter_pattern_add_include "test_filter" "login"
    assert_success
    
    print_test "包含user应该通过"
    local event='{"message":"user login success"}'
    _filter_pattern_apply "test_filter" "$event"
    assert_success
    
    print_test "不包含user或login应该拒绝"
    event='{"message":"system startup"}'
    ! _filter_pattern_apply "test_filter" "$event"
    assert_success
    
    print_test "添加排除模式"
    _filter_pattern_add_exclude "test_filter" "debug"
    assert_success
    
    print_test "包含debug应该被排除"
    event='{"message":"debug user info"}'
    ! _filter_pattern_apply "test_filter" "$event"
    assert_success
}

#-----------------------------------------------------------------------------
# 测试频率限制过滤器
#-----------------------------------------------------------------------------
function test_filter_rate_limit() {
    print_header "测试频率限制过滤器"
    
    source "$PROJECT_ROOT/scripts/logger/filters/filter_rate_limit.sh"
    
    print_test "初始化过滤器(最大5条/秒)"
    _filter_rate_limit_init "test_filter" 5 10 "false"
    assert_success
    
    print_test "快速发送日志(超出限制)"
    local passed=0
    local rejected=0
    
    for i in {1..20}; do
        local event="{\"message\":\"测试日志 $i\"}"
        if _filter_rate_limit_apply "test_filter" "$event"; then
            ((passed++))
        else
            ((rejected++))
        fi
    done
    
    echo "    通过: $passed, 拒绝: $rejected"
    [[ $rejected -gt 0 ]]
    assert_success
    
    print_test "启用去重功能"
    _filter_rate_limit_reset "test_filter"
    _filter_rate_limit_init "test_filter" 100 10 "true"
    assert_success
    
    print_test "重复消息应该被拒绝"
    event='{"message":"重复消息"}'
    _filter_rate_limit_apply "test_filter" "$event"
    ! _filter_rate_limit_apply "test_filter" "$event"
    assert_success
}

#-----------------------------------------------------------------------------
# 主测试函数
#-----------------------------------------------------------------------------
function main() {
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║         Logger模块 v2.0 功能集成测试                         ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    echo "测试环境:"
    echo "  项目根目录: $PROJECT_ROOT"
    echo "  Shell版本: $BASH_VERSION"
    echo ""
    
    # 运行所有测试
    test_buffer
    test_context
    test_sanitizer
    test_filter_level
    test_filter_pattern
    test_filter_rate_limit
    
    # 显示测试结果
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║  测试结果统计                                                ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo "  总计: $TOTAL_TESTS"
    echo "  通过: $PASSED_TESTS"
    echo "  失败: $FAILED_TESTS"
    echo ""
    
    if [[ $FAILED_TESTS -eq 0 ]]; then
        echo "✅ 所有测试通过！"
        return 0
    else
        echo "❌ 有 $FAILED_TESTS 个测试失败"
        return 1
    fi
}

# 运行测试
main "$@"

